package com.example.demo.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /* String token = request.getHeader("user_token");   //这里需要向客户端获取一下token，来校验一下身份
        Claims claims = TokenUtil.parseJWT(token);
        if(claims==null){
            response.setStatus(401);
            return false;
        }
        return true;*/

        HttpSession session = request.getSession(false);
        log.info("jinxing lanjie");
        if(session==null||session.getAttribute("userInfo")==null){
            response.sendRedirect("/sign-in.html");   //未登录的状态就跳转到登录页面，这是一种方式，如果是想要前端
           return false;                            //去跳转那么就可以：response.status(401),return false;
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
